
let fs = require('fs');
let path = require('path');
let router = require('koa-router')();

function searchControllers(defaultDir){
    let files = fs.readdirSync(defaultDir);
    let resultFiles = files.filter((fileName) => {
        return fileName.endsWith('.js') && fileName !== 'index.js';
    });

    return resultFiles;
}

function registeForEachFile(files,currentPath){
    files.forEach(item => {
        let tmpPath = path.join(currentPath, item);
        let routerObj = require(tmpPath);
        for (let r in routerObj) {
            let arrValue=routerObj[r];
            let type = routerObj[r][0];

            if (type === 'get') {
            
                if(arrValue.length===2){
                    let fn=arrValue[1];
                    router.get(r, fn);
                }else{
                    let auth=arrValue[1];
                    let fn=arrValue[2];
                    router.get(r,auth,fn);
                }                
            } else {
                if(arrValue.length===2){
                    let fn=arrValue[1];
                    router.post(r, fn);
                }else{
                    let auth=arrValue[1];
                    let fn=arrValue[2];
                    router.post(r,auth,fn);
                }
            }
        }
    })
}


// 3、将本文件当作控制器目录的入口，在app.js当中作为中间注册

module.exports = function(dir){
    let defaultDir=dir || '/controllers';
    // 项目当前绝对路径
    let root = path.resolve('.');
    // 获得控制器的绝对路径
    let resultControllerPath = path.join(root, defaultDir);

    // 获得控制器目录下的所有路由文件
    let files=searchControllers(resultControllerPath);

    // 注册定义的路由
    registeForEachFile(files,resultControllerPath);

    //返回待在app执行的注册函数
    return router.routes();
};